<!--
 * @Author: actor
 * @Date: 2023-11-09 10:18:27
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-19 15:32:38
 * @FilePath: \i-hos-app\shared\emr\src\views\rpo\rpoMain.vue
 * @Description: 知识库主体页面
-->
<template>
  <Main class="mainPage">
    <template #header>
      <!-- 头部 -->
      <div class="mainPage-header">
        <div class="header">
          <div class="left">
            <el-icon size="17" color="#79bbff"><Notebook /></el-icon>
            分类：{{ activetreeList[0].emrKnowledgeBaseCategoryName }}
          </div>
          <div class="right">
            <el-button
              type="primary"
              :icon="isFormVisible ? 'Filter' : 'Search'"
              @click="() => (isFormVisible = !isFormVisible)"
              >{{ isFormVisible ? '隐藏' : '查询' }}</el-button
            >
            <el-button @click="handleAdd" icon="Plus">新增</el-button>
          </div>
        </div>

        <div :class="['serachForm', isFormVisible ? '' : 'close']">
          <SerachForm :serachKey="serachKey" @updateSerach="serachTable" />
        </div>
      </div>
    </template>

    <!-- 表格列表 -->
    <template v-if="emrPageShare.tableList?.length" #default>
      <el-table
        :data="emrPageShare.tableList"
        border
        ref="multipleTableRef"
        @selection-change="handleSelectionChange"
        @row-click="handClickRow"
      >
        <!-- <el-table-column type="index" label="序号" width="42" /> -->
        <el-table-column type="selection" width="40" />
        <el-table-column prop="categoryName" label="分类" />
        <el-table-column prop="emrKnowledgeBaseMainName" label="名称" />
        <el-table-column prop="emrKnowledgeBaseMainCode" label="编码" />
        <!-- <el-table-column prop="createTime" label="创建时间" width="130" />
        <el-table-column prop="updateTime" label="更新时间" width="130" /> -->
        <el-table-column prop="" label="操作" width="83">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click.stop="handleRemove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分页 -->
    <template v-if="emrPageShare.tableList?.length" #pageFooter>
      <div class="table-footer">
        <div>
          <el-button @click="handleRemove">批量删除</el-button>
          <el-button @click="clearSelection()">清空选择</el-button>
        </div>
        <el-pagination
          small
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="emrPageShare.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="emrPageShare.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="emrPageShare.totalPage"
        >
        </el-pagination>
      </div>
    </template>

    <!-- 数据为空的状态 -->
    <el-empty v-if="!emrPageShare.tableList?.length" description="暂无数据" :image-size="150" style="height: 100%"></el-empty>
  </Main>

  <!-- 添加分类弹窗 -->
  <el-dialog
    v-model="dialogvisible"
    :title="`添加/编辑` + activetreeList[0].emrKnowledgeBaseCategoryName"
    width="300"
    align-center
    draggable
  >
    <el-form :model="sortForm" label-width="45px">
      <el-form-item label="分类">
        <v-combogrid
          :style="{ padding: 0 }"
          v-model="sortForm.parentId"
          v-model:inputlabel="sortForm.fatherName"
          row-key="emrKnowledgeBaseCategoryId"
          :data="activetreeList"
          :fields="['emrKnowledgeBaseCategoryId', 'emrKnowledgeBaseCategoryName']"
          pid="parentId"
          height="300"
          width="300"
          :columns="[{ prop: 'emrKnowledgeBaseCategoryName', title: '名称' }]"
          :requestJSON-event="['change', 'enter']"
          :tree-props="{ children: 'childList' }"
          :disabled="bogridDisabled"
        ></v-combogrid>
      </el-form-item>
      <el-form-item label="名称">
        <el-input clearable placeholder="请输入名称" v-model="sortForm.name" />
      </el-form-item>
      <el-form-item label="编码">
        <el-input clearable placeholder="请输入编码" v-model="sortForm.code" />
      </el-form-item>
      <el-form-item>
        <el-button
          @click="
            (): void => {
              dialogvisible = !dialogvisible
            }
          "
          >取消</el-button
        >
        <el-button type="primary" @click="commitAdd">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 详情抽屉 -->
  <el-drawer v-model="tableDetailsVisible" direction="rtl" :with-header="false" size="500">
    <el-icon class="el-icon--left drawerClose" @click="() => (tableDetailsVisible = false)"><Close /></el-icon>
    <RpoDetails :id="`${sortForm.id as string}`" />
  </el-drawer>
</template>

<script setup lang="ts">
  import { Ref, ref, reactive, getCurrentInstance, watch } from 'vue'
  import { ElTable } from 'element-plus'
  // 自定义组件
  import RpoDetails from './rpoDetails.vue'
  import SerachForm from '../../components/common/serachForm.vue'

  // 配置类型约束
  import { IPageShare, ISerachKey, ISortForm } from '../../interface/pageShare'
  // 仓库数据以及解构 store的配置数据
  import { useEmrPageShare } from '../../store/emrPageShare'
  const emrPageShare: IPageShare = useEmrPageShare()

  const { proxy } = getCurrentInstance() as any
  let isFormVisible: Ref<boolean> = ref(false), // 是否开启查询栏
    dialogvisible: Ref<boolean> = ref(false), // 添加分类数据开启和关闭
    bogridDisabled: Ref<boolean> = ref(false), // 编辑新增数据控制分类数据是否可以修改
    tableDetailsVisible: Ref<boolean> = ref(false), // 详情抽屉开启个关闭
    activetreeList: any = reactive([]), // 当前下所有的分类
    multipleTableRef = ref<InstanceType<typeof ElTable>>(), // 表格ref
    multipleSelection = ref<any[]>([]), // 表格选中的数据
    sortForm: ISortForm = reactive({
      // 弹层回填数据
      type: '',
      parentId: '',
      fatherName: '',
      id: '',
      name: '',
      code: '',
    }),
    serachKey: ISerachKey[] = reactive([
      // 分类对应的表格查询关键字
      {
        label: '编码',
        type: 'text',
        value: '',
      },
      {
        label: '名称',
        type: 'text',
        value: '',
      },
    ])

  // 监听更新对应数据
  watch(
    (): any => [emrPageShare.activetreeList, dialogvisible.value],
    (): any => {
      if (!!emrPageShare.activetreeList) {
        activetreeList = []
        activetreeList.push(emrPageShare.activetreeList)
      }
      if (!dialogvisible.value) {
        sortForm.type = ''
        sortForm.parentId = ''
        sortForm.fatherName = ''
        sortForm.id = ''
        sortForm.name = ''
        sortForm.code = ''
      }
    },
    {
      immediate: true,
      deep: true,
    }
  )

  // 通过关键子查询
  const serachTable = (flag?: String): void => {
    let params: any = {}
    for (let obj of serachKey) {
      if (!flag) {
        switch (obj.label) {
          case '编码':
            params.code = obj.value
            break
          case '名称':
            params.keyword = obj.value
            break
        }
      } else {
        obj.value = ''
      }
    }
    emrPageShare.fetchCategoryTable(proxy, params)
  }

  // 删除当前对应的分类
  const backfillTreeData = (flag?: any): void => {
    activetreeList = []
    if (!!flag) {
      function getTreeItem(data: any, id: number) {
        data.map((item: any) => {
          if (item.emrKnowledgeBaseCategoryId == id) {
            activetreeList.push(item)
          } else {
            if (item.childList) getTreeItem(item.childList, id)
          }
        })
      }
      if (flag.emrKnowledgeBaseMainCategoryId == emrPageShare.activetreeList.emrKnowledgeBaseCategoryId) {
        activetreeList.push(emrPageShare.activetreeList)
      } else {
        getTreeItem(emrPageShare.activetreeList.childList, flag.emrKnowledgeBaseMainCategoryId)
      }
    } else {
      activetreeList.push(emrPageShare.activetreeList)
    }
    sortForm.parentId = activetreeList[0].emrKnowledgeBaseCategoryId
    sortForm.fatherName = activetreeList[0].emrKnowledgeBaseCategoryName
    bogridDisabled.value = !activetreeList[0].childList
  }

  // 新增
  const handleAdd = (): void => {
    dialogvisible.value = !dialogvisible.value
    // 回填数据
    backfillTreeData()
  }

  // 编辑
  const handleEdit = (flag: any): void => {
    dialogvisible.value = !dialogvisible.value
    // 回填数据
    sortForm.id = flag.emrKnowledgeBaseMainId
    sortForm.name = flag.emrKnowledgeBaseMainName
    sortForm.code = flag.emrKnowledgeBaseMainCode
    backfillTreeData(flag)
  }

  // 新增或者编辑修改提交
  const commitAdd = () => {
    const url: string = APP_GLOBAL.API['EMR']['category-table-saveOrUpdate']
    proxy.$http
      .requestJSON('post', url, {
        emrKnowledgeBaseMainCategoryId: sortForm.parentId,
        emrKnowledgeBaseMainId: sortForm.id,
        emrKnowledgeBaseMainName: sortForm.name,
        emrKnowledgeBaseMainCode: sortForm.code,
      })
      .then((res: any) => {
        if (res.data) {
          dialogvisible.value = !dialogvisible.value
          emrPageShare.fetchCategoryTable(proxy)
        }
      })
  }

  const removeTableData = (flag: any): void => {
    const url: string = APP_GLOBAL.API['EMR']['category-table-remove']
    let ids = []
    for (let item of flag) {
      ids.push(item.emrKnowledgeBaseMainId)
    }
    proxy.$http.requestJSON('post', url, ids).then((res: any) => {
      if (res.data) {
        emrPageShare.fetchCategoryTable(proxy)
      }
    })
  }

  // 删除表格数据（单行或者批量删除）
  const handleRemove = (flag?: any): void => {
    let arr: any = []
    if (Array.isArray(flag) && flag[0].emrKnowledgeBaseMainId) {
      arr = flag
    } else {
      if (flag.emrKnowledgeBaseMainId) arr.push(flag)
    }
    removeTableData(arr.length > 0 ? arr : multipleSelection.value)
  }

  // 清空所有选择
  const clearSelection = (): void => {
    multipleTableRef.value!.clearSelection()
  }

  // 批量选择
  const handleSelectionChange = (flag: any): void => {
    multipleSelection.value = flag
  }

  // 点击行至详情
  const handClickRow = (row: any): void => {
    tableDetailsVisible.value = true
    sortForm.id = row.emrKnowledgeBaseMainId.toString()
  }

  // 修改分页
  const handleSizeChange = (val: number) => {
    emrPageShare.$patch((state: IPageShare): void => {
      state.pageSize = val
    })
    emrPageShare.fetchCategoryTable(proxy)
  }
  const handleCurrentChange = (val: number) => {
    emrPageShare.$patch((state: IPageShare): void => {
      state.pageNum = val
    })
    emrPageShare.fetchCategoryTable(proxy)
  }
</script>

<style lang="scss" scoped>
  .mainPage {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    .serachForm {
      padding: 10px 0;
      transition: all 0.2s;
      &.close {
        height: 0;
        overflow: hidden;
        padding: 0;
      }
    }
    &-header {
      width: 100%;
      .header {
        display: flex;
        justify-content: space-between;
        padding: 6px 0;
        margin: -10px 0 0;
        border-bottom: 1px solid #d8dce5;
        align-items: center;
        .left,
        .right {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #333;
        }
      }
    }
    .table-footer {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .drawerClose {
    position: absolute;
    top: 15px;
    right: 15px;
    cursor: pointer;
    font-size: 22px;
    color: #777777;
  }
</style>
